﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;

namespace BuyTrainTicket
{
    public partial class QueryTask : PhoneApplicationPage
    {
        string username;
        string password;
        string postData = "";

        public QueryTask()
        {
            InitializeComponent();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.TryGetValue<String>("username", out username);
            settings.TryGetValue<String>("password", out password);
            if (username == null || password == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            sendRequest(Util.host + "/servlet/Buy12306Servlet?action=querytask&password=" + password + "&username=" + username + "&type==querytask&version=8.1");


        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    if ((bool)responseObj.GetValue("isSuccess") == true)
                    {

                        TaskCollection tasks = new TaskCollection();
                        JArray dataArray = (JArray)responseObj.GetValue("data");
                        foreach (JToken data in dataArray)
                        {
                            int statusvalue = (int)((JObject)data).GetValue("status");
                            String order_time = (String)((JObject)data).GetValue("order_time");
                            String scheduledtime = (String)((JObject)data).GetValue("scheduledtime");
                            String key = (String)((JObject)data).GetValue("key");
                            String datevalue = key.Split(':')[3];
                            String fromvalue = key.Split(':')[4];
                            String tovalue = key.Split(':')[5];
                            String last_msgvalue = (String)((JObject)data).GetValue("last_msg");

                            String convertvalue = "未知";
                            if (statusvalue == -1)
                            {
                                convertvalue = "计划中";
                            }
                            else if (statusvalue == 0)
                            {
                                convertvalue = "成功";
                            }
                            else if (statusvalue == 1)
                            {
                                convertvalue = "进行中";
                            }
                            else if (statusvalue == 2)
                            {
                                convertvalue = "失败";
                            }
                            TaskObject task = new TaskObject("状态:" + convertvalue, "自动订购:" + fromvalue + "->" + tovalue, key, "order", "开始时间:" + order_time, "下次计划时间:" + scheduledtime, last_msgvalue);
                            tasks.Add(task);
                        }

                        JArray queryArray = (JArray)responseObj.GetValue("query");
                        foreach (JToken query in queryArray)
                        {
                            int statusvalue = (int)((JObject)query).GetValue("status");
                            String key = (String)((JObject)query).GetValue("key");
                            String last_msgvalue = (String)((JObject)query).GetValue("last_msg");

                            String convertvalue = "未知";
                            if (statusvalue == -1)
                            {
                                convertvalue = "计划中";
                            }
                            else if (statusvalue == 0)
                            {
                                convertvalue = "成功";
                            }
                            else if (statusvalue == 1)
                            {
                                convertvalue = "进行中";
                            }
                            else if (statusvalue == 2)
                            {
                                convertvalue = "失败";
                            }
                            TaskObject task = new TaskObject("状态:" + convertvalue, "查询:" + key, key, "query", "", "", last_msgvalue);
                            tasks.Add(task);
                        }
                        Dispatcher.BeginInvoke(() =>
                        {
                            taskList.ItemsSource = tasks;
                        });
                    }
                    else
                    {
                        string errMsg = (string)responseObj.GetValue("errMsg");
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(errMsg);
                        });
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(response.StatusCode.ToString());
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }

        }

        private void cancel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TaskObject item = ((FrameworkElement)sender).DataContext as TaskObject;
            if (item != null)
            {
                if (item.Status.Contains("成功") || item.Status.Contains("失败"))
                {
                    MessageBox.Show("此状态不可取消");
                }
                else
                {
                    postData = "key=" + item.Key + "&type=" + item.Type;
                    sendCancelRequest(Util.host + "/servlet/Buy12306Servlet?action=cancel&type=cancel&password=" + password + "&username=" + username + "&version=8.1");
                }
            }
        }

        private void viewlog_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TaskObject item = ((FrameworkElement)sender).DataContext as TaskObject;
            if (item != null)
            {
                postData = "key=" + item.Key + "&type=" + item.Type;
                sendViewLogRequest(Util.host + "/servlet/Buy12306Servlet?action=viewlog&type=viewlog&password=" + password + "&username=" + username + "&version=8.1");
            }
        }

        void sendCancelRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getCancelRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getCancelRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getCancelResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getCancelResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    string errMsg = (string)responseObj.GetValue("errMsg");
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(errMsg);
                    });

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(response.StatusCode.ToString());
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }
        }

        void sendViewLogRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getViewLogRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getViewLogRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getViewLogResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getViewLogResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(responseStr.Replace("<br/>", "\n"));
                    });

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(response.StatusCode.ToString());
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }
        }
    }




}